package com.pharmacy.SaleManage.service;// 文件位置: src/main/java/com/pharmacy/SaleManage/service/impl/SaleRecordServiceImpl.java


import com.pharmacy.InventoryManage.entity.Inventory;
import com.pharmacy.InventoryManage.service.InventoryService;
import com.pharmacy.SaleManage.dao.SaleRecordMapper;
import com.pharmacy.SaleManage.entity.SaleRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class SaleRecordServiceImpl implements SaleRecordService {

    @Autowired
    private SaleRecordMapper saleRecordMapper;

    @Autowired
    private InventoryService inventoryService;

    @Override
    public List<SaleRecord> getAllSaleRecords() {
        return saleRecordMapper.findAllSaleRecords();
    }

    @Override
    public SaleRecord getSaleRecordById(Integer id) {
        return saleRecordMapper.findSaleRecordById(id);
    }

    @Override
    public List<SaleRecord> getSaleRecordsByDateRange(Date startDate, Date endDate) {
        return saleRecordMapper.findSaleRecordsByDateRange(startDate, endDate);
    }

    @Override
    public List<SaleRecord> getSaleRecordsByMedicineId(Integer medicineId) {
        return saleRecordMapper.findSaleRecordsByMedicineId(medicineId);
    }

    @Override
    public List<SaleRecord> getSaleRecordsByOperatorId(Integer operatorId) {
        return saleRecordMapper.findSaleRecordsByOperatorId(operatorId);
    }

    @Override
    @Transactional
    public boolean addSaleRecord(SaleRecord saleRecord) {
        // 检查库存是否充足
        boolean hasEnoughStock = inventoryService.checkStock(
                saleRecord.getMedicineId(), saleRecord.getQuantity());

        if (!hasEnoughStock) {
            return false;
        }

        // 插入销售记录
        int result = saleRecordMapper.insertSaleRecord(saleRecord);
        if (result > 0) {
            // 更新库存
            Inventory inventory = inventoryService.getInventoryByMedicineId(saleRecord.getMedicineId());
            if (inventory != null) {
                int newQuantity = inventory.getQuantity() - saleRecord.getQuantity();
                inventoryService.updateInventoryQuantity(saleRecord.getMedicineId(), newQuantity);
            }
            return true;
        }
        return false;
    }

    @Override
    public Double getTotalSalesByDateRange(Date startDate, Date endDate) {
        return saleRecordMapper.getTotalSalesByDateRange(startDate, endDate);
    }
}